# 公共方法文件
import string
import datetime
import hashlib
import urllib
from xml.etree import ElementTree as ET
import time
import random
from Puer.constant import constant
import json


# 公共支付接口
def payment_interface(cfg_data):
    data = {}
    check_data = {}
    is_success = False
    # 随机字符串，不超过32位
    wx_nonce_str = ''.join([(string.ascii_letters + string.digits)[x] for x in random.sample(range(0, 62), 20)])

    data['appid'] = constant.APP_ID
    data['attach'] = constant.COMPANY_NAME
    data['body'] = cfg_data.get("body")
    data['mch_id'] = constant.MCH_ID
    data['nonce_str'] = wx_nonce_str
    data['notify_url'] = 'https://www.retux.cn/pay'
    data['openid'] = cfg_data.get("user_id")
    data['out_trade_no'] = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1, 256))
    data['spbill_create_ip'] = cfg_data.get("client_ip")
    data['total_fee'] = cfg_data.get("money")
    data['trade_type'] = 'JSAPI'

    count = 1
    test = ""
    for i in sorted(data.keys()):
        v = data.get(i)
        if count == 1:
            test = test + '{key}={value}'.format(key=i, value=v)
        else:
            test = test + '&{key}={value}'.format(key=i, value=v)
        count = count + 1
    test = '%s&key=%s' % (test, constant.PAYMENT_KEY)
    sign = hashlib.md5(test.encode('utf-8')).hexdigest().upper()
    data['sign'] = sign
    xml = []
    for k in sorted(data.keys()):
        v = data.get(k)
        if k == 'detail' and not v.startswith('<![CDATA['):
            v = '<![CDATA[{}]]'.format(v)
        xml.append('<{key}>{value}</{key}>'.format(key=k, value=v))
    get_data = '<xml>{}</xml>'.format(''.join(xml))

    req = urllib.request.Request('https://api.mch.weixin.qq.com/pay/unifiedorder')

    with urllib.request.urlopen(req, data=get_data.encode('utf-8')) as response:
        html = response.read().decode("utf8")
        response.close()

    tree = ET.fromstring(html)
    result = {}
    if tree.tag == 'xml':
        for child in tree:
            result[child.tag] = child.text
    print(result)
    if result['return_code'] == 'SUCCESS' and result['result_code'] == 'SUCCESS':
        is_success = True
        check_data['appId'] = constant.APP_ID
        check_data['timeStamp'] = int(time.time())
        check_data['nonceStr'] = result['nonce_str']
        check_data['package'] = 'prepay_id=' + result['prepay_id']
        check_data['signType'] = 'MD5'
        count = 1
        test = ""
        for i in sorted(check_data.keys()):
            v = check_data.get(i)
            if count == 1:
                test = test + '{key}={value}'.format(key=i, value=v)
            else:
                test = test + '&{key}={value}'.format(key=i, value=v)
            count = count + 1

        test = '%s&key=%s' % (test, constant.PAYMENT_KEY)
        sign = hashlib.md5(test.encode('utf-8')).hexdigest().upper()
        check_data['paySign'] = sign
        return check_data, is_success
    return check_data, is_success


# 支付取消
def cancel_payment():
    pass


# 公共方法文件
def get_page_start_end(page: object, row: object, obj_result: object) -> object:
    """
    :param page: 页面当前显示页数
    :param row: 页面当前显示行数
    :param obj_result: 查询数据库结果集
    :return: start:数据库数据点起点 stop:数据数据点终点
    """
    if page is not None and row is not None:
        start = (int(page) - 1) * int(row)
        stop = start + int(row)
    else:
        start = 0
        stop = len(obj_result)
    return start, stop


# 消费方式转码
def paykind_status_to_zh(status):
    return constant.CONSUME if status == 1 else constant.RECHARGE


def paykind_zh_to_status(paykind):
    if paykind == constant.CONSUME:
        return 1
    if paykind == constant.RECHARGE:
        return 2
    # 0代表全部状态
    return 0


# 订单状态与状态码映射
def orders_status_zh_mapping(orders_status):
    orders_status_zh_dict = {
        constant.PENDING_PAYMENT: 1,
        constant.TO_BE_DELIVERED: 2,
        constant.PENDING_RECEIPT: 3,
        constant.COMPLETED: 4,
        constant.CANCELLED: 5
    }
    for key, value in orders_status_zh_dict.items():
        if key == orders_status:
            return value
        elif type(value) is int and value == orders_status:
            return key
    return constant.ALL


# 物流公司代号转换中文
def delivery_company_transform(delivery_company_name):
    for key, value in constant.DELIVERY_COMPANY.items():
        if value == delivery_company_name:
            return key
    return None


# 获取定位信息
def get_location_info(longitude, latitude):
    url = constant.LOCATION_INTERFACE % (longitude, latitude)
    req = urllib.request.Request(url)
    with urllib.request.urlopen(req) as response:
        content = response.read().decode("utf8")
        response.close()
    location_info = json.loads(content)
    return location_info.get("location", {}).get("addressComponent", {}).get("city", constant.DEFAULT_LOCATION_CITY)
